package com.EmployeeButler.controller;


import cn.dev33.satoken.util.SaResult;
import com.EmployeeButler.entity.Salary;
import com.EmployeeButler.entity.User;
import com.EmployeeButler.service.ISalaryService;
import com.EmployeeButler.utils.MyTool;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2024-06-13
 */
@Controller
@RequestMapping("/salary")
public class SalaryController {

    @Autowired
    private ISalaryService salaryService;

    @GetMapping("/me")
    public String getSalaryOfMe(Model model) {
        Integer loginId = MyTool.getLoginId();
        List<Salary> salaries = salaryService.list(new QueryWrapper<Salary>()
                .eq("user_id", loginId));
        model.addAttribute("salaries", salaries);
        return "user/my_salary";
    }



    @GetMapping("/search")
    public String search(@RequestParam(required = false) String keyword, Model model) {
        // 定义用户列表
        List<Salary> salaries;

        // 检查关键字是否为空
        if (keyword == null || keyword.isEmpty()) {
            salaries = salaryService.list();
        } else {
            salaries = salaryService.list(new QueryWrapper<Salary>()
                    .like("user_id", keyword));
        }
        // 将用户列表添加到模型中
        model.addAttribute("salaries", salaries);
        return "admin/salaries";
    }

    @GetMapping("/remove/{id}")
    @ResponseBody
    public SaResult removeById(@PathVariable Integer id) {
        salaryService.removeById(id);
        return SaResult.ok();
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id,Model model) {
        Salary salary = salaryService.getById(id);
        model.addAttribute("salary", salary);
        return "admin/salary_edit";
    }


    @GetMapping
    public String getSalary(Model model) {
        List<Salary> salaries = salaryService.list();
        model.addAttribute("salaries", salaries);
        return "admin/salaries";
    }

    @GetMapping("/{userId}")
    public String toPayroll(@PathVariable Integer userId, Model model) {
        model.addAttribute("userId", userId);
        return "admin/put_salary";
    }

    @PostMapping
    @ResponseBody
    public SaResult addSalary(Salary salary) {
        salary.setTotal(salary.getBase() + salary.getBonus());
        if (salary.getId() != null) {
//            更新
            salaryService.updateById(salary);
            return SaResult.ok();
        }
//        新增
        salaryService.save(salary);
        return SaResult.ok();
    }
}
